package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

import java.text.SimpleDateFormat;

/**
 * Author: Felix
 * Date: 2021/11/29
 * Desc: 独立访客的计算
 * 需要启动的进程
 * zk、kafka、logger.sh、BaseLogApp、UniqueVisitorApp
 * 执行流程
 * -运行模拟生成日志数据的jar
 * -将生成的日志发送给Nginx
 * -Nginx进行负载均衡，将请求转发给三台日志采集服务器进行处理
 * -日志采集服务器将日志发送到kafka的ods_base_log主题中
 * -BaseLogApp从ods_base_log主题中读取数据，进行分流
 * >启动日志   dwd_start_log
 * >页面日志   dwd_page_log
 * >曝光日志   dwd_display_log
 * -UniqueVisitorApp从dwd_page_log中读取数据
 */
public class UniqueVisitorApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 设置流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);

        //TODO 2.设置检查点(略)

        //TODO 3.从Kafka中读取数据
        //3.1 声明消费主题以及消费者组
        String topic = "dwd_page_log";
        String groupId = "unique_visitor_app_group";

        //3.2 创建消费者对象
        FlinkKafkaConsumer<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);

        //3.3 消费数据封装流
        DataStreamSource<String> kafkaDS = env.addSource(kafkaSource);

        //TODO 4.对流中的数据进行类型转换   jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(JSON::parseObject);

        //jsonObjDS.print(">>>>>");

        //TODO 5.按照mid对数据进行分组
        KeyedStream<JSONObject, String> keyedDS = jsonObjDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));

        //TODO 6.去重
        SingleOutputStreamOperator<JSONObject> filterDS = keyedDS.filter(
            new RichFilterFunction<JSONObject>() {
                private ValueState<String> lastVisitDateState;
                private SimpleDateFormat sdf;

                @Override
                public void open(Configuration parameters) throws Exception {
                    sdf = new SimpleDateFormat("yyyyMMdd");
                    ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<String>("valueStateDescriptor", String.class);
                    //设置状态的失效时间
                    StateTtlConfig stateTtlConfig = StateTtlConfig.newBuilder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                        .build();
                    valueStateDescriptor.enableTimeToLive(stateTtlConfig);
                    lastVisitDateState = getRuntimeContext().getState(valueStateDescriptor);
                }

                @Override
                public boolean filter(JSONObject jsonObj) throws Exception {
                    //判断是否是从其它页面跳转过来的，如果是，直接过滤掉
                    String lastPageId = jsonObj.getJSONObject("page").getString("last_page_id");
                    if (lastPageId != null && lastPageId.length() > 0) {
                        return false;
                    }
                    //----利用状态保存历史访问的日期，判断是否曾经访问过----
                    //从状态中获取上次访问日期
                    String lastVisitDate = lastVisitDateState.value();
                    //获取当前日志访问日志
                    String curDate = sdf.format(jsonObj.getLong("ts"));

                    //判断今天是否访问过
                    if (lastVisitDate != null && lastVisitDate.length() > 0 && curDate.equals(lastVisitDate)) {
                        //已经访问过  直接将再次访问的数据给过滤掉
                        return false;
                    } else {
                        //没有访问过 ，将当前访问的日期放到状态中保存起来
                        lastVisitDateState.update(curDate);
                        return true;
                    }

                }
            }
        );

        filterDS.print(">>>>>");

        //TODO 7.将去重之后的独立访客 写到kafka的dwm主题中
        filterDS
            .map(jsonObj->jsonObj.toJSONString())
            .addSink(MyKafkaUtil.getKafkaSink("dwm_unique_visitor"));

        env.execute();
    }
}
